from rest_framework import serializers
from fdfs_client.client import Fdfs_client
from rest_framework import status
from rest_framework.response import Response

from apps.goods.models import SKUImage, SKU


class ImageSerializer(serializers.ModelSerializer):
    """
    商品规格选项序列化器
    """
    class Meta:
        model = SKUImage
        fields = "__all__"

    # 默认方法没有保存到FastDFS,不满足需求,所以需要重新create方法
    # 局部的保存业务逻辑
    def create(self, validated_data):
        """
        重写保存图片方法
        """
        # 1.获取前端sku对象
        sku = validated_data["sku"]
        # 2.获取前端传递的图片数据
        image = validated_data["image"]
        # 3.连接FastDfs
        client = Fdfs_client('/home/python/Desktop/meiduo48_one/meiduo_mall/meiduo_mall/utils/fastdfs/client.conf')
        # 4.上传图片
        # upload_by_buffer:是上传图片二进制
        res = client.upload_by_buffer(image.read())
        # 5.判断是否成功
        if res["Status"] != "Upload successed.":
            raise serializers.ValidationError("上传图片失败")
        # 6.提取图片连接地址
        path = res.get("Remote file_id")
        # 7.保存图片数据
        img = SKUImage.objects.create(sku=sku,image=path)
        return img

    #########图片更新重写################
    def update(self, instance, validated_data):
        #  连接FastDFS
        client = Fdfs_client('/home/python/Desktop/meiduo48_one/meiduo_mall/meiduo_mall/utils/fastdfs/client.conf')
        #  上传图片
        image = validated_data["image"]
        res = client.upload_by_buffer(image.read())
        #  判断是否成功
        if res["Status"] != "Upload successed.":
            raise serializers.ValidationError("上传图片失败")
        #  提取图片连接地址
        path = res.get("Remote file_id")
        # 更新图片
        instance.image = path
        instance.save()
        return instance





class SimpleSKUSerializer(serializers.ModelSerializer):
    """
    商品SKU序列化器
    """
    class Meta:
        model = SKU
        fields = ["id","name"]
